/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
<template>
  <el-dialog
    title="当前任务设置"
    v-if="closeDialog"
    :visible.sync="closeDialog"
    append-to-body
    fullscreen
    custom-class="task-dialog"
  >
    <m-popover
      ref="popover"
      @close="close"
      @ok="_ok"
    >
      <template slot="content">
        <div class="box">
          <el-form
            ref="form"
            :model="form"
            label-width="120px"
            size="mini"
            label-position="left"
            :rules="rules"
          >
            <el-form-item
              label="任务名称"
              prop="taskName"
            >
              <el-input
                v-model="form.taskName"
                placeholder="请输入名称（必填）"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="任务类型"
              prop="taskType"
            >
              <el-select
                v-model="form.taskType"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="工作流名称"
              prop="workflowName"
            >
              <el-select
                v-model="form.workflowName"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运行标志">
              <el-radio-group v-model="form.runningMark">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">禁止执行</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="缓存执行">
              <el-switch
                v-model="form.cache"
                active-color="#33317e"
                inactive-color="#e9e9e9"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="form.remark"
                maxlength="300"
                rows="3"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item
              label="任务优先级"
              prop="taskPriority"
            >
              <el-select
                v-model="form.taskPriority"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Worker分组"
              prop="workerGroup"
            >
              <el-select
                v-model="form.workerGroup"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="环境名称"
              prop="environmentName"
            >
              <el-select
                v-model="form.environmentName"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="任务组名称"
              prop="taskGroupName"
            >
              <el-select
                v-model="form.taskGroupName"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="组内优先级">
              <el-input-number
                v-model="form.groupPriority"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="失败重试次数">
              <el-input-number
                v-model="form.retryTimes"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
                data-unit="次"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="失败重试间隔">
              <el-input-number
                v-model="form.retryInterval"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
                data-unit="分"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="CPU配额">
              <el-input-number
                v-model="form.cpuQuota"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
                data-unit="%"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="最大内存">
              <el-input-number
                v-model="form.maxMemory"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
                data-unit="MB"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="延时执行时间">
              <el-input-number
                v-model="form.delayTimes"
                style="width: 100%;"
                controls-position="right"
                :step="1"
                :min="0"
                :max="999"
                data-unit="分"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="超时告警">
              <el-switch
                v-model="form.timeoutAlarm"
                active-color="#33317e"
                inactive-color="#e9e9e9"
              >
              </el-switch>
            </el-form-item>
            <el-form-item
              label="脚本"
              prop="rawScript"
            >
              <div class="form-mirror">
                <textarea
                  id="mcode-python-mirror"
                  name="mcode-python-mirror"
                  style="opacity: 0;"
                >
              </textarea>
              </div>
            </el-form-item>
            <el-form-item label="资源">
              <treeselect
                v-model="resourceList"
                :multiple="true"
                maxHeight="200"
                :options="resourceOptions"
                :normalizer="normalizer"
                :value-consists-of="valueConsistsOf"
                :disabled="false"
                style="width: 100%;"
                :placeholder="$t('Please select resources')"
              >
                <div
                  slot="value-label"
                  slot-scope="{ node }"
                >{{ node.raw.fullName }}<span
                    class="copy-path"
                    @mousedown="_copyPath($event, node)"
                  >&nbsp; <em
                      class="el-icon-copy-document"
                      data-container="body"
                      data-toggle="tooltip"
                      :title="$t('Copy path')"
                    ></em> &nbsp; </span></div>
              </treeselect>
            </el-form-item>
            <el-form-item label="自定义参数">
              <m-local-params
                ref="refLocalParams"
                @on-local-params="_onLocalParams"
                :udp-list="form.localParams"
                :hide="true"
              >
              </m-local-params>
            </el-form-item>
            <el-form-item label="前置任务">
              <el-select
                v-model="form.predecessorTask"
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  label="按量计费"
                  :value="0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </m-popover>
  </el-dialog>
</template>
<script>
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import Clipboard from 'clipboard'
  import mPopover from '@/module/components/popup/popover'
  import i18n from '@/module/i18n'
  import mLocalParams from '@/conf/home/pages/dag/_source/formModel/tasks/_source/localParams.vue'
  import codemirror from '@/conf/home/pages/resource/pages/file/pages/_source/codemirror'
  let editor
  export default {
    name: 'close-dialog',
    data () {
      return {
        closeDialog: false,
        item: null,
        form: {
          id: '',
          taskName: '',
          taskType: null,
          workflowName: null,
          runningMark: 0,
          cache: false,
          remark: '',
          taskPriority: '',
          workerGroup: '',
          environmentName: '',
          taskGroupName: '',
          groupPriority: 0,
          retryTimes: 0,
          retryInterval: 0,
          cpuQuota: 0,
          maxMemory: 0,
          delayTimes: 0,
          timeoutAlarm: false,
          rawScript: '',
          localParams: [],
          predecessorTask: '',
        },
        backfillItem: {},
        resourceList: [],
        resourceOptions: [],
        normalizer (node) {
          return {
            label: node.name
          }
        },
        info: {},
        rules: {
          taskName: [
            { required: true, message: '请输入任务名称', trigger: 'blur' },
          ],
          taskType: [
            { required: true, message: '请选择任务类型', trigger: ['change', 'submit'] },
          ],
          workflowName: [
            { required: true, message: '请选择工作流', trigger: ['change', 'submit'] },
          ],
          taskPriority: [
            { required: true, message: '请选择任务优先级', trigger: ['change', 'submit'] },
          ],
          workerGroup: [
            { required: true, message: '请选择Worker分组', trigger: ['change', 'submit'] },
          ],
          rawScript: [
            { required: true, message: '请输入脚本', trigger: ['submit'] },
          ],
        }
      }
    },
    methods: {
      _copyPath (e, node) {
        e.stopPropagation()
        let clipboard = new Clipboard('.copy-path', {
          text: function () {
            return node.raw.fullName
          }
        })
        clipboard.on('success', handler => {
          this.$message.success(`${i18n.$t('Copy success')}`)
          // Free memory
          clipboard.destroy()
        })
        clipboard.on('error', handler => {
          // Copy is not supported
          this.$message.warning(`${i18n.$t('The browser does not support automatic copying')}`)
          // Free memory
          clipboard.destroy()
        })
      },
      /**
       * return localParams
       */
      _onLocalParams (a) {
        this.form.localParams = a
      },
      /**
       * Processing code highlighting
       */
      _handlerEditor () {
        // editor
        editor = codemirror('mcode-python-mirror', {
          mode: 'python',
          readOnly: false
        })

        this.keypress = () => {
          if (!editor.getOption('readOnly')) {
            editor.showHint({
              completeSingle: false
            })
          }
        }

        // Monitor keyboard
        editor.on('keypress', this.keypress)

        editor.setValue(this.form.rawScript)

        return editor
      },
      /**
       * verification
       */
      _verification () {
        // rawScript 验证
        if (!editor.getValue()) {
          this.$message.warning(`${i18n.$t('Please enter script(required)')}`)
          return false
        }

        // localParams Subcomponent verification
        if (!this.$refs.refLocalParams._verifProp()) {
          return false
        }
        this.form.rawScript = editor.getValue()
      },
      show (item) {
        this.item = item
        this.closeDialog = true
        setTimeout(() => {
          this._handlerEditor()
        }, 200)
      },
      _ok () {
        this._verification()
        this.$refs.form.validate(async (valid) => {
          if (!valid) return
          try {
            console.log('123', this.form)
          } catch (error) {
            console.log('error===>', error)
          }
        })
      },
      close () {
        this.item = null
        this.form = {}
        this.$refs.form.clearValidate()
        this.closeDialog = false
      }
    },
    destroyed () {
      editor.toTextArea() // Uninstall
      editor.off($('.code-python-mirror'), 'keypress', this.keypress)
    },
    components: { mPopover, mLocalParams, Treeselect }
  }
</script>
<style lang="scss" scoped>
/deep/.task-dialog {
  width: 750px !important;
}
</style>
<style lang="scss" scoped>
/deep/.border {
  border-bottom: 1px dashed #dadada;
  padding-top: 8px !important;
  .el-form-item--mini.el-form-item {
    margin-bottom: 3px !important;
  }
}
.box {
  padding: 0 20px;
  padding-top: 15px;
  max-height: calc(100vh - 200px);
  overflow-y: scroll;
  .title {
    width: 64px;
    height: 20px;
    font-size: 16px;
    font-family: PingFang SC, PingFang SC-600;
    font-weight: 600;
    text-align: LEFT;
    color: #333333;
    line-height: 20px;
    margin-bottom: 10px;
  }
}
/deep/.el-form-item--mini.el-form-item {
  margin-bottom: 15px;
}
::v-deep .el-switch__core {
  border-radius: 3px !important;
  &::after {
    border-radius: 2px !important;
    // background-color: #f5f5f5;
  }
}
::v-deep.el-input-number .el-input__inner {
  text-align: left !important;
}
.el-input-number[data-unit] {
  --el-input-number-unit-offset-x: calc(40px + 4px);
}
.el-input-number--small[data-unit] {
  --el-input-number-unit-offset-x: calc(32px + 4px);
}
.el-input-number[data-unit]::after {
  content: attr(data-unit);
  position: absolute;
  top: 0;
  right: var(--el-input-number-unit-offset-x);
  color: #8d8d8d;
  height: 100%;
  display: flex;
  align-items: center;
}
.el-input-number[data-unit] .el-input__inner {
  padding-right: calc(1em + var(--el-input-number-unit-offset-x) + 4px);
}
</style>
